from django.contrib.auth.backends import ModelBackend

from users.models import User
from users.utils import get_user


class MeiduoModelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 判断请求的来源
        if request is None:  # 序列化器中，对数据验证调用的validate方法中，调用authenticate方法的时候没有传入request，所以可以以此判断是超级用户还是普通用户
            # vue组件，从库中检测是否是后台管理用户的逻辑
            try:
                user = User.objects.get(username=username, is_staff=True)
            except User.DoesNotExist:
                return None
        else:
            # 顾客，顾客逻辑
            user = get_user(username)

        if user and user.check_password(password):
            return user
        else:
            return None



